package net.oov.identify.support;

import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;


/**
 * 
 * 数值分布模型
 * x表示x轴分布的数值
 * y表示y轴分布的对应x值（大于等于）的数量
 * 
 * @author huangsui.cn
 *
 */
public class Distribution {
	
	private String xName = "数值";
	private String yName = "数量";
	private int[] x = new int[10];
	private int[] y = new int[10];
	
	public Distribution(int stepLength, int startingValue) {
		super();
		init(stepLength, startingValue);
	}
	
	public Distribution(int stepLength, int startingValue, String xName, String yName) {
		super();
		this.xName = xName;
		this.yName = yName;
		init(stepLength, startingValue);
	}
	
	public Distribution(int[] x) {
		super();
		this.x = x;
	}
	
	private void init(int stepLength, int startingValue){
		int v = startingValue;
		for(int i=0;i<x.length;i++){
			x[i] = v;
			v = v + stepLength;
		}
	}
	
	public void add(Double d, int amount){
		y[getXSubscript(d)] += amount;
	}
	
	/**
	 * 根据d值，获取对应x的下标（大于等于）
	 * @param d
	 */
	private int getXSubscript(Double d){
		int s1 = 0;
		int s2 = x.length-1;
		
		while(true){
			if(s1 >= s2)return s1;
			int mid = (s1+s2)/2;
			if(d>=x[mid] && d<x[mid+1]){
				return mid;
			}else if(d>=x[mid+1]){
				s1 = mid+1;
			}else if(d<x[mid]){
				s2 = mid;
			}
			
		}
	}
	
	public int getXValue(int subscript){
		return x[subscript];
	}
	
	public int getYValue(int subscript){
		return y[subscript];
	}

	@Override
	public String toString() {
		StringBuilder s = new StringBuilder();
		for(int i=0;i<x.length;i++){
			s.append(x[i]);
			s.append(":");
			s.append(y[i]);
			s.append(" ");
			
		}
		return s.toString();
	}

	public void out2Excel(String file, String sheetName) throws IOException{
		
		HSSFWorkbook wb = new HSSFWorkbook();
		HSSFSheet s = wb.createSheet();
		wb.setSheetName(0, sheetName,HSSFCell.ENCODING_UTF_16);
		
		HSSFRow row = null;
		HSSFCell cell = null;
		int firstBlankLine = 0;
		
		//生成表格字段名
		row = s.createRow(firstBlankLine);
		cell = row.createCell((short) 0);
		cell.setEncoding(HSSFCell.ENCODING_UTF_16);
		cell.setCellValue(xName);
		cell = row.createCell((short) 1);
		cell.setEncoding(HSSFCell.ENCODING_UTF_16);
		cell.setCellValue(yName);
		firstBlankLine++;
		
		//加入数据
		for(int i=0;i<x.length;i++){
			row = s.createRow(firstBlankLine+i);
			cell = row.createCell((short) 0);
			cell.setEncoding(HSSFCell.ENCODING_UTF_16);
			cell.setCellValue(x[i]);
			cell = row.createCell((short) 1);
			cell.setEncoding(HSSFCell.ENCODING_UTF_16);
			cell.setCellValue(y[i]);
		}
		
		FileOutputStream fos = new FileOutputStream(file);
		wb.write(fos);
		fos.close();
	}


	
}
